const router = require('express').Router()
const { wrap, DMS, uuid } = require('../tool')
const { Article, Article_classif, Op, sequelize } = require('../config/sql')
const formidable = require('formidable')
const { join, extname } = require('path')
const { public } = require('../config')

// 上传文章信息
const uploadDir = join(public, '/userupimage')
router.post('/upinfo', wrap(async (req, res, next) => {
   const { account } = req.user
   const form = formidable({
      uploadDir,
      filename: (name, ext, part) => {
         return uuid() + extname(part.originalFilename)
      },
      allowEmptyFiles: false
   })
   form.parse(req, async (err, fields, files) => {
      if (err) {
         next('500')
      }
      const { cover_type, abstract, type, so, main, tag, classif, id } = fields
      if (!id) throw '316'
      let cover = Object.values(files).map(a => a.newFilename)
      const el = cover_type == 2 ? 3 : cover_type
      for (let i = 0; i < el; i++) {
         const url = fields['cover_' + i]
         cover.splice(i, 0, url)
      }

      try {
         if (classif) {
            const classifArr = classif.split(' ')
            for (const iterator of classifArr) {
               await Article_classif.findOrCreate({
                  where: {
                     uid: account,
                     name: iterator
                  },
                  defaults: {
                     name: iterator
                  }
               })
            }
         }
         cover = cover.join(' ').split(/ +/).join(' ').trim()
         const article = await Article.update({
            cover_type,
            abstract,
            type,
            so,
            tag,
            classif,
            cover
         }, {
            where: {
               uid: account,
               id
            }
         })
         if (!article) throw '316'
         res.send({
            code: 200
         })
      } catch (error) {
         console.log(error);
         next(error)
      }
   })
}))

// 获取文章列表
router.get('/list', wrap(async (req, res) => {
   const { user, query: { state, year, month, type, classif, screen, so, del } } = req
   const and = []
   const where = {
      delete: 0,
      uid: user.account
   }

   console.log(req.query);
   if (type) where.type = type
   if (state) where.state = state
   if (so) where.so = so
   if (del) where.delete = del
   if (year) and.push(sequelize.where(sequelize.fn('year', sequelize.col('createdAt')), '=', year))
   if (month) and.push(sequelize.where(sequelize.fn('month', sequelize.col('createdAt')), '=', month))
   if (screen) and.push({
      [Op.or]: [
         sequelize.fn('locate', screen, sequelize.col('title')),
         sequelize.fn('locate', screen, sequelize.col('main'))
      ]
   })
   if (classif) and.push(sequelize.fn('locate', classif, sequelize.col('classif')))

   if (and.length) where[Op.and] = and
   const articleSql = await Article.findAll({
      attributes: ['id', 'title', 'createdAt', 'pushdateAt', 'read', 'cover', 'type', 'state'],
      where,
      // 按发布时间升序排列
      order: [
         ['pushdateAt', 'DESC']
      ]
   })
   const article = []
   for (const iterator of articleSql) {
      article.push(
         Object.assign({
            agree: await iterator.agree,
            collection: await iterator.collection,
         }, iterator.dataValues)
      )
   }
   res.send({
      code: 200,
      article
   })
}))

// 获取近期文章列表
router.get('/nearup', wrap(async (req, res) => {
   const { user } = req
   console.log(user);
   const article = await Article.findAll({
      attributes: ['id', 'title', 'createdAt', 'pushdateAt', 'read', 'agree', 'collection', 'state', 'abstract'],
      where: {
         uid: user.account,
         delete: 0,
         [Op.or]: [
            { state: 0 },
            { state: 1 }
         ],
         // 筛选近七天的文章
         createdAt: {
            [Op.gt]: new Date((new Date()) - DMS(7))
         }
      },
      // 按发布时间升序排列
      order: [
         ['pushdateAt', 'DESC']
      ]
   })
   res.send({
      code: 200,
      article
   })
}))

// 获取近期发布文章列表
router.get('/nearpush', wrap(async (req, res) => {
   const { user } = req
   const articleSql = await Article.findAll({
      attributes: ['id', 'title', 'createdAt', 'pushdateAt', 'read', 'abstract'],
      where: {
         uid: user.account,
         delete: 0,
         state: 1,
         // 筛选近七天的文章
         pushdateAt: {
            [Op.gt]: new Date((new Date()) - DMS(7))
         }
      },
      // 按发布时间升序排列
      order: [
         ['pushdateAt', 'DESC']
      ]
   })
   const article = []
   for (const iterator of articleSql) {
      article.push(
         Object.assign({
            agree: await iterator.agree,
            collection: await iterator.collection,
         }, iterator.dataValues)
      )
   }
   res.send({
      code: 200,
      article
   })
}))

// 获取原文信息
router.get('/info', wrap(async (req, res) => {
   const { user, query: { id } } = req
   if (!id) throw '316'
   const [article] = await Article.findAll({
      attributes: ['id', 'main', 'title', 'cover_type', 'type', 'cover', 'so', 'abstract', 'classif', 'tag'],
      where: {
         uid: user.account,
         id
      }
   })
   const classif = await Article_classif.findAll({
      attributes: ['id', 'name'],
      where: {
         uid: user.account
      }
   })
   if (!article) throw '404'
   res.send({
      code: 200,
      article,
      classif
   })
}))

// 上传文章
router.post('/upload', wrap(async (req, res) => {
   const { user, body: { title, main } } = req
   if (!title) throw '316'
   const data = await Article.create({
      title,
      main,
      uid: user.account,
      state: 0
   })
   res.send({
      code: 200,
      msg: '保存成功',
      id: data.getDataValue('id'),
      date: new Date
   })
}))

//  更新文章
router.post('/updata', wrap(async (req, res) => {
   const { user, body: { title, main, id } } = req
   if (!title || !id) throw '316'
   await Article.update({
      title,
      main,
      state: 0
   }, {
      where: {
         uid: user.account,
         id
      }
   })
   res.send({
      code: 200,
      msg: '保存成功',
      id,
      date: new Date
   })
}))

// 发布文章
router.post('/push', wrap(async (req, res) => {
   const { user, body: { id } } = req
   if (!id) throw '316'
   const [data] = await Article.update({
      pushdateAt: new Date,
      state: 1,
      'delete': 0
   }, {
      where: {
         uid: user.account,
         id,
      }
   })
   res.send({
      code: 200
   })
}))

// 删除文章
router.get('/delete', wrap(async (req, res) => {
   const { user, query: { id } } = req
   // console.log(user.account, id);
   // const [article] = await Article.update({
   //    'delete': 1
   // }, {
   //    attribute: ['id'],
   //    where: {
   //       uid: 1,
   //       id: 33
   //    }
   // })
   // if (!article) throw '325'

   const [article] = await Article.update({
      'delete': 1
   }, {
      attribute: ['id'],
      where: {
         uid: user.account,
         'delete': 0,
         id
      }
   })
   if (!article) throw '325'
   res.send({
      code: 200
   })
}))

module.exports = router